package com.wangyadong.hobby.schedule.jobtask.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NioDemo {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel server = ServerSocketChannel.open();
        server.bind(new InetSocketAddress(9099), 1024);
        server.configureBlocking(false);
        Selector selector = Selector.open();
        server.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            //阻塞当前线程
            int select = selector.select();

            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            ByteBuffer allocate = ByteBuffer.allocate(1024);
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()) {
                    ServerSocketChannel serverAttachment = (ServerSocketChannel) key.channel();
                    if (serverAttachment == null) {
                        continue;
                    }
                    SocketChannel channel = serverAttachment.accept();
                    //
                    channel.configureBlocking(false);
                    channel.register(selector, SelectionKey.OP_READ);

                } else if (key.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    socketChannel.configureBlocking(false);
                    socketChannel.read(allocate);
                    System.out.println(new String(allocate.array()));
                    //读取完成
                    socketChannel.register(selector, SelectionKey.OP_WRITE);
                } else if (key.isWritable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    channel.configureBlocking(false);
                    channel.write(ByteBuffer.wrap(getRespHeadInfo().getBytes()));
                    channel.close();
                    selector.wakeup();
                }
            }
        }


    }

    public static String getRespHeadInfo() {

        String proolVersion = "HTTP/1.1";


        String contentType = "application/json";
        StringBuffer responseStr = new StringBuffer();
        // 拼装HTTP响应头信息
        responseStr
                .append(proolVersion + " 200  " + " ok").append("\r\n")
                .append("Content-Type: " + contentType).append("\r\n")
                .append("Connection: close/Keep-Alive").append("\r\n")
                .append("\r\n")
                .append("\twyd->" + System.currentTimeMillis());
        return responseStr.toString();
    }
}
